package cn.qiao.mdc.spring;

import cn.qiao.mdc.consts.Constants;
import jakarta.servlet.*;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(Integer.MIN_VALUE)
public class MDCFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            MDC.put(Constants.TRACE_ID, Constants.getTraceId());
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.remove(Constants.TRACE_ID);
        }
    }
}
